<template>
  <div class="flex-main">
    <!-- html转图片 -->
    <span class="m-shadow" v-if="isHtmlCanvas" @click="closeHtmlCanvas"></span>
    <!-- <img class="real_pic htmlCavas" :src="dataURL" width="100%" v-if="isHtmlCanvas" />
    <div class="imageWrapper" ref="imageWrapper">
        <div class="canvas-div">
          <img src="@/assets/appointment/appointment_shop.png" alt="" class="projectImg">
          <div class="m-proTitle">
            <p>{{detail.ProjectName || detail.GoodsName || detail.CardKindName}}</p>
            <b>&yen;{{detail.Price || detail.SellMoney}}</b>
            
            <div>
              <p></p>
              <canvas id="qrcode-canvas" class="canvas-ewm"></canvas>
            </div>
          </div>
        </div>
    </div> -->

    <html-canvas v-if="isHtmlCanvas">
      <!-- 需要转换图片的dom元素 -->
        <div class="canvas-div">
          <img src="@/assets/appointment/appointment_shop.png" alt="" class="projectImg">
          <div class="m-proTitle">
            <p>{{detail.ProjectName || detail.GoodsName || detail.CardKindName}}</p>
            <b>&yen;{{detail.Price || detail.SellMoney}}</b>
            
            <div>
              <p></p>
              <canvas id="qrcodeCanvas" class="canvas-ewm"></canvas>
            </div>
          </div>
        </div>
    </html-canvas>

    <div class="flex-body">
      <detail-slider :imglist="detail.imgList || ''" 
      :Avatar="detail.Avatar" 
      :is_pic="detail.is_pic"
      :cover="detail.cover"></detail-slider>

      <div class="m-proTitle">
        <p>{{detail.ProjectName || detail.GoodsName || detail.CardKindName}}</p>
        <b>&yen;{{detail.Price || detail.SellMoney}}</b>
        <div>
          <p>累计销售{{detail.ProjectSales || detail.SaleNum}}笔</p>
          <img src="@/assets/images/scancode.png" @click="toImage">
        </div>
      </div>

      <div class="m-disbox mb">
        <div class="m-dis mb">
          <span>宝贝评价({{evaluate_total}})</span>
          <em class="m-more" @click="toEvaluetion">查看全部</em>
        </div>
        <evaluetion-item v-for="(item,index) in evaluatelist" :key="index" :evaluate="item"></evaluetion-item>
      </div>

      <div class="m-detail">
        <p class="m-title mb">商品详情</p>
        <div class="m-detail-html" v-html="detail.Detail || detail.content"></div>
        <!-- <img src="@/assets/images/p_02.jpg" alt> -->
      </div>
    </div>
    <div class="flex-bottom">
      <div class="m-detail-bottom">
        <div>
          <span @click="minusNum">-</span>
          <input type="number" v-model="num" name="number">
          <span @click="addNum">+</span>
        </div>
        <div class="m-cart" @click="addCart">加入购物车</div>
        <div class="m-buy" @click="showSpecBtn">立即购买</div>
      </div>
    </div>
    <projuect-spec @closeSpec="closeSpec" v-if="showSpec" :detail="detail" :goodsid="goodsid" :type="type"></projuect-spec>
  </div>
</template>
<script>
/**产品2、项目1、卡项3 */
import { getGoodDetail, getGoodEvaluate, addCard,payOrder,getProjecthasCard} from "@/api/views";
let QRCode = require('qrcode');
// import QRCode from 'qrcode';
import { setTimeout } from 'timers';
import html2canvas from 'html2canvas';
import htmlCanvas from '@/components/html2canvas';
export default {
  name: "",
  data() {
    return {
      dataURL: '',
      showSpec: false,
      num: 1,
      type: "", //商品类型 产品2、项目1、卡项3
      goodsid: "", //商品id
      detail: "", //详情内容
      evaluatelist:[],  //评价列表
      evaluate_total:0,     //评价数量
      isHtmlCanvas:false,
    };
  },
  components: {
    detailSlider: () => import("@/model/projectDetail/detailSlider"),
    evaluetionItem: () => import("@/model/evaluetion/evaluetionItem"),
    projuectSpec: () => import("@/model/projectDetail/projectSpec"),
    htmlCanvas,
  },
  methods: {
    toImage() {
      this.isHtmlCanvas = true;
    },
    closeHtmlCanvas() {
      console.log('关闭');
      this.isHtmlCanvas = false;
    },
    //   获取评价列表
    goodEvaluate() {
      let that = this;
      let param = {
        goods_id: that.goodsid,
        type: that.type, //商品类型：1项目 2是产品 3：卡
        status: "", //评价状态 ： 1:好评 ；2中评 ； 3差评
        page: 1,
        list_rows: 6
      };
      getGoodEvaluate(param).then(response => {
          that.evaluatelist = response.list.data;
          that.evaluate_total = response.list.total;
      }).catch(error=>{});
    },
    // 查看更多宝贝评价
    toEvaluetion() {
      this.$router.push({ path: "/evaluetion",query:{goodsid:this.goodsid,type:this.type} });
    },
    // 数量减少
    minusNum() {
      let num = this.num;
      if (num < 2) {
        this.$toast("不能再少啦~");
      } else {
        num--;
      }
      this.num = num;
    },
    // 数量增加
    addNum() {
      let num = this.num;
      if(num>=this.detail.StockNum){
        this.$toast('库存不够了o(╥﹏╥)o');
      }else{
        num++;
        this.num = num;
      }
      
    },
    // 加入购物车
    addCart() {
      let that = this;
      let ispay = that.detail.IsPay;
      let num = that.num;   //选择的购买数量
      if(num>that.detail.StockNum) {
        this.$toast('您需要的数量太多了o(╥﹏╥)o');
        that.num = that.detail.StockNum;
        return false;
      }
      if(ispay != '1') {
          this.$toast('请到店支付');
          return false;
      }
      let param = {
          goods_id:that.goodsid,
          type:that.type,
          quantity:that.num,
          customer_id:that.$utils.uid,       //用户id
      }
      addCard(param).then(result=>{
          that.$toast('已添加至购物车，前往购物车查看');
      }).catch(error=>{

      })
    },
    // 立即购买，显示规格层:项目类型才有规格选择
    showSpecBtn() {
      let that = this;
      let type = this.type;   //1项目 2是产品 3：卡
      let detail = that.detail;
      let ispay = detail.IsPay;
      if(type==1){
        // 获取项目包含卡项，如果没有对应卡项，直接购买
        getProjecthasCard({ProjectId:that.goodsid}).then((result) => {
            let list = result.list;
            if(list.length<1){    //没有对应卡项
              if(ispay != '1') {    //假支付
                  console.log('假支付的产品价格'+detail.Price);
                  if(detail.Price==0 || detail.Price=='' || detail.SellMoney==0 || detail.SellMoney=='' ){
                    that.$toast('请到店支付');
                    return false;
                  }
                  let param = {
                    customer_id:that.$utils.uid,
                    total_amount:detail.Price || detail.SellMoney,
                    type:that.type,
                    goods_id:that.goodsid,
                    CardClassId:that.goodsid,
                    project_id:that.goodsid,
                    goods:detail.ProjectName || detail.GoodsName || detail.CardKindName,
                    quantity:that.num,
                    price:detail.Price || detail.SellMoney
                  }
                  payOrder(param).then(result=>{
                    that.$toast('购买成功');
                    setTimeout(() => {
                      that.$router.push({name:'myOrders',query:{type:1}})
                    }, 500);
                    
                  }).catch(error=>{});
              }else{
                console.log('真支付的产品价格'+detail.Price);
                if(detail.Price==0 || detail.Price=='' || detail.SellMoney==0 || detail.SellMoney=='' ){
                  that.$toast('请到店支付');
                  return false;
                }
                let buyData = {
                    Id:that.goodsid,
                    type:that.type,
                    quantity:that.num,
                }
                this.actionBuydata(buyData);        //存到store中
                this.$router.push({name:'payment'})
              }
            }else{
              this.showSpec = true;
            }
        }).catch((err) => {
            
        });
        
      }else{
        if(ispay != '1') {    //假支付
            if(detail.Price==0 || detail.Price=='' || detail.SellMoney==0 || detail.SellMoney=='' ){
              that.$toast('请到店支付');
              return false;
            }
            let param = {
              customer_id:that.$utils.uid,
              total_amount:detail.Price || detail.SellMoney,
              type:that.type,
              goods_id:that.goodsid,
              CardClassId:that.goodsid,
              project_id:that.goodsid,
              goods:detail.ProjectName || detail.GoodsName || detail.CardKindName,
              quantity:that.num,
              price:detail.Price || detail.SellMoney
            }
            payOrder(param).then(result=>{
              that.$toast('购买成功');
              setTimeout(() => {
                that.$router.push({name:'myOrders',query:{type:1}})
              }, 500);
            }).catch(error=>{});
        }else{
          if(detail.Price==0 || detail.Price=='' || detail.Price==null || detail.SellMoney==0 || detail.SellMoney=='' || detail.SellMoney==null ){
            that.$toast('请到店支付');
            return false;
          }
          let buyData = {
              Id:that.goodsid,
              type:that.type,
              quantity:that.num,
          }
          this.actionBuydata(buyData);        //存到store中
          this.$router.push({name:'payment'})
        }
      }
    },
    // 关闭选择规格层
    closeSpec() {
      this.showSpec = false;
    }
  },
  mounted() {
    let that = this;
    this.$indicator.open('加载中...');
    let goodsid = this.$route.query.goodsid;
    let _type = this.$route.query.type;
    let _url = "";
    let user = null;
    let param = {};
    switch (_type) {
      case "1": //项目
      case 1:
        _url = "/project/project_detail";
        param = {
          ProjectId: goodsid,
          CustomerId: user || ""
        };
        break;
      case "2": //产品
      case 2:
        _url = "/goods/goods_detail";
        param = {
          GoodsId: goodsid,
          CustomerId: user || ""
        };
        break;
      case "3": //卡项
      case 3:
        _url = "/card/card_detail";
        param = {
          CardClassId: goodsid,
          CustomerId: user || ""
        };
        break;
      default:
        break;
    }
    that.goodsid = goodsid;
    that.type = _type;
    // 请求详情
    getGoodDetail(param, _url)
      .then(result => {
        this.$indicator.close();
        that.detail = result.detail || result.list;

        that.goodEvaluate();        //评价列表

        setTimeout(()=>{
          // 生成二维码
          let canvas = document.getElementById('qrcodeCanvas');
          let _HOST = window.location.host;
          let bannerUrl = "http://" + _HOST + "/dist/index?superiorid=" + that.$utils.uid ;     //指定到首页
          // QRCode.toCanvas(canvas, bannerUrl, (error) => {
          //     if (error) {
          //     console.log(error)
          //     } else {
          //     console.log('success')
          //     }
          // })
          QRCode.toCanvas('qrcodeCanvas', {  
              width: 100,  
              height: 100, // 高度  
              text: bannerUrl, // 二维码内容
              image: ''  
              // render: 'canvas' // 设置渲染方式（有两种方式 table和canvas，默认是canvas）  
              // background: '#f0f'  
              // foreground: '#ff0'  
          })
        },300)
        
      })
      .catch(err => {});
  }
};
</script>
<style lang="less" scoped src="@/less/projectDetail/projectDetail.less"></style>
<style scoped>
.m-detail-html>>>img{
    width: 100%;
}
</style>

